package com.fingard.dsp.bank.directbank.jsjnrcb01;

import java.util.Calendar;
import java.util.Date;

import com.fingard.constant.Format;
import com.fingard.dsp.bank.directbank.bankInterface.ITransaction;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7515TodayTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.Req7516HisTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.RetAtsTrans;
import com.fingard.dsp.bank.reqrespobj.transaction.detail.RetAtsTransDetail;
import com.fingard.text.StringHelper;
import com.fingard.util.DateHelper;
import com.fingard.xml.XmlTextReader;
import com.fingard.xml.XmlTextWriter;

public class JSJNRCB01Transaction extends JSJNRCB01Base implements ITransaction {

	//采用流处理方式
	//1、循环调用readRecord()读取一个请求明细，然后写入发银行的XML对象
	//2、发银行
	//3、循环调用XmlTextReader.read()读取一个银行返回节点，赋值返回ATS的明细对象，
	//   然后调用writeRetDetail()，写入返回ATS的明细
	public RetAtsTrans d_7516_HisTrans(Req7516HisTrans p_req7516) throws Exception{
		//历史明细查询返回ATS的对象
		RetAtsTrans retAts = new RetAtsTrans(p_req7516.reqHeader);
		String tmpRespCode = "";
		String tmpRespInfo = "";
		retAts.writeStart();//写返回ATS的统一头部信息
		try {
			//tmpClndrStepTo.get(Calendar.MONTH) MONTH是从0开始编的，意味着0是1月，11是12月
			Calendar tmpCalendarFrom = Calendar.getInstance();
			tmpCalendarFrom.setTime(p_req7516.getDateFrom());
			
			Calendar tmpCalendarTo = Calendar.getInstance();
			tmpCalendarTo.setTime(p_req7516.getDateTo());
			
			int tmpIntDateFrom = 0;
			int tmpIntDateTo = 0;
			//按自然月循环查询
			while(tmpIntDateFrom<=tmpIntDateTo && tmpRespCode.length() == 0){
				Calendar tmpClndrStepTo = Calendar.getInstance();
				tmpClndrStepTo.setTime(tmpCalendarFrom.getTime());
				//判断是否跨月
				if(DateHelper.compareMonth(tmpCalendarFrom, tmpCalendarTo) == -1){
					//跨月则设置为月末
					tmpClndrStepTo.set(Calendar.DAY_OF_MONTH, tmpClndrStepTo.getActualMaximum(Calendar.DAY_OF_MONTH));
				}
				else{
					tmpClndrStepTo.setTime(tmpCalendarTo.getTime());
				}
				JSJNRCB01Header tmpBnkHeader = new JSJNRCB01Header(); 
				String opName = "B2EActTrsQry";
				tmpBnkHeader.TransCode = opName;
				int queryNumber = 20;//查询的笔数
				int beginNumber = -1;//查询的起始笔数
				int totalCount = 0;
				XmlTextWriter xmlWriter = new XmlTextWriter();//发银行报文的XML对象

				writeCommenHeader(xmlWriter,tmpBnkHeader);
				while(beginNumber<=totalCount && tmpRespCode.length() == 0){//分页查询
					
					if(beginNumber < 0){
						beginNumber = 1;
					}					
					xmlWriter.writeStartElement("Body");
					xmlWriter.writeStartElement("List");
					xmlWriter.writeStartElement("Map");
					xmlWriter.writeElementString("AcNo", p_req7516.actNum);
					xmlWriter.writeElementString("BeginDate", Format.Date10Format.format(tmpCalendarFrom.getTime()));
					xmlWriter.writeElementString("EndDate", Format.Date10Format.format(tmpClndrStepTo.getTime()));
					
					xmlWriter.writeElementString("currentIndex", String.valueOf(queryNumber));
					xmlWriter.writeElementString("pageSize", String.valueOf(beginNumber));
					xmlWriter.writeEndDocument();
					
					String[] tmpStrRet = sendToBank(xmlWriter.toXmlString(),opName);
					XmlTextReader tmpBkReader;
					
					if(tmpStrRet[0].length() > 0){//判断通讯是否失败
						tmpRespCode = "-1";
						tmpRespInfo = tmpStrRet[1];
						break;
					}
					StringBuilder tmpSbMsg = new StringBuilder();
					tmpBkReader = loadBankRespXmlReader(tmpStrRet[1], tmpSbMsg);
					if(tmpBkReader == null){//判断加载xml是否成功
						tmpRespCode = "-1";
						tmpRespInfo = tmpSbMsg.toString();
						break;
					}	
					String returnCode = tmpBkReader.getFirstText("/transaction/Head/IBSReturnCode");
					String returnMsg = tmpBkReader.getFirstText("/transaction/Head/IBSReturnMsg");
					if(returnCode == null || !returnCode.equals("000000")){//判断报文是否无效
						tmpRespCode = "-1";
						tmpRespInfo = returnMsg;
						break;
					}
					String bkStrTotalCount = tmpBkReader.getFirstText("/transaction/Body/rowcnt");
					if(StringHelper.isNullOrEmpty(bkStrTotalCount)){
						break;
					}
					int totalCountCmp = Integer.parseInt(bkStrTotalCount);
					if(totalCount == 0){
						totalCount = totalCountCmp;
					}
					if(totalCount != totalCountCmp){
						tmpRespCode = "-1";
						tmpRespInfo = "相同条件银行返回的总笔数"+totalCountCmp+"与上次"+totalCount+"不相同";
						break;
					}
					
					String acctNo = tmpBkReader.getFirstText("/transaction/Head/AcNo");
					if(StringHelper.isNullOrEmpty(acctNo)){
						acctNo = p_req7516.actNum;
					}
					int tmpRdCount = 0;
					while(tmpBkReader.read("/transaction/Body/List/Map")){
						tmpRdCount++;
						RetAtsTransDetail tmpRetDetail = new RetAtsTransDetail();
						tmpRetDetail.actNum = acctNo;
						String currency = tmpBkReader.readedXElement.getSingleText("Currency");
						if(StringHelper.hasAnyChar(currency)){
							tmpRetDetail.cur = this.convertCurToATS(currency);
						}
						tmpRetDetail.accBal = tmpBkReader.readedXElement.getSingleText("Balance");
						String txAmount = tmpBkReader.readedXElement.getSingleText("Amount");
						String tranFlag = tmpBkReader.readedXElement.getSingleText("DCFlag");
						
						if (tranFlag.equals("D")){//0：借     1：贷
							tmpRetDetail.cdFlag = "1";
							if(txAmount.indexOf("-")>=0){
								tmpRetDetail.cdFlag = "2";
							}
                        }
                        else if (tranFlag.equals("C")){
                        	tmpRetDetail.cdFlag = "2";
                        	if(txAmount.indexOf("-")>=0){
								tmpRetDetail.cdFlag = "1";
							}
                        }
                        else{
                        	tmpRespCode = "-1";
    						tmpRespInfo = "银行返回的借贷标志不符合预期";
    						break;
                        }
						tmpRetDetail.tranAmt = txAmount.replace("-", "");
	                    tmpRetDetail.tranDate = tmpBkReader.readedXElement.getSingleText("TransDate");

	                    String transTime = tmpBkReader.readedXElement.getSingleText("TransTime");
	                    if (transTime.length() > 6)
	                    {
	                    	tmpRetDetail.tranTime = tmpRetDetail.tranDate + " " + transTime.substring(0,2)+":"+transTime.substring(3,5)+":"+transTime.substring(6,8);
	                    }
	                    else
	                    {
	                    	tmpRespCode = "-1";
    						tmpRespInfo = "银行返回的交易时间格式"+tmpBkReader.readedXElement.getSingleText("transTime")+"不符合预期";
    						break;
	                    }
	                    tmpRetDetail.valueDate = tmpRetDetail.tranDate;											
						
						tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("Toacct");
						if(StringHelper.isNullOrEmpty(tmpRetDetail.recAccNum)){
							tmpRetDetail.recAccNum = tmpBkReader.readedXElement.getSingleText("customerAcctNo");
						}
	                    tmpRetDetail.recAccName = tmpBkReader.readedXElement.getSingleText("Toacna");
	                    tmpRetDetail.comment = tmpBkReader.readedXElement.getSingleText("Remark");
						retAts.writeRetDetail(tmpRetDetail);
					}
					beginNumber += tmpRdCount;
					if(tmpRdCount == 0){
						break;
					}
				}
				
				tmpCalendarFrom = tmpClndrStepTo;
				tmpCalendarFrom.add(Calendar.DAY_OF_MONTH, 1);
				tmpIntDateFrom = Integer.parseInt(Format.Date8Format.format(tmpCalendarFrom.getTime()));
				tmpIntDateTo = Integer.parseInt(Format.Date8Format.format(tmpCalendarTo.getTime()));
			}
		} catch (Exception e) {
			tmpRespCode = "-1";
			tmpRespInfo = e.getMessage();
			e.printStackTrace();
		}
		if(tmpRespCode.equals("-1")){
			retAts = new RetAtsTrans(p_req7516.reqHeader);
			retAts.writeStart();//写返回ATS的统一头部信息
			retAts.writeRespCode(tmpRespCode);
			retAts.writeRespInfo(tmpRespInfo);
		}
		else if(retAts.getWrittenRdCount() == 0){
			retAts.writeRespCode("0");
			retAts.writeRespInfo("交易为空");
		}
		retAts.writeEnd();
		return retAts;
	}
	
	//当日明细查询调用历史明细查询方法
	public RetAtsTrans d_7515_TodayTrans(Req7515TodayTrans p_req7515) throws Exception{
		//通用b2e0035
		Req7516HisTrans tmpReq7516 = new Req7516HisTrans(p_req7515.reqHeader);
		tmpReq7516.actArea = p_req7515.actArea;
		tmpReq7516.actCur = p_req7515.actCur;
		tmpReq7516.actNum = p_req7515.actNum;
		String tmpStrToday = Format.Date8Format.format(new Date());
		tmpReq7516.dateFrom = tmpStrToday;
		tmpReq7516.dateTo = tmpStrToday;
		return 	d_7516_HisTrans(tmpReq7516);
	}
}
